/*********************************************************************************
 *      Copyright:  (C) 2022 Zhang Changxing<ZhangChangxingVIP@163.com>
 *                  All rights reserved.
 *
 *       Filename:  socket.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(04/14/2022)
 *         Author:  Zhang Changxing <ZhangChangxingVIP@163.com>
 *      ChangeLog:  1, Release initial version on "04/14/2022 08:36:37 PM"
 *                 
 ********************************************************************************/

#include "socket.h"

/*  Initialize socket  */
int socket_init(char *listen_ip, int port)
{
	struct sockaddr_in 	servaddr;
	int					rv = -1;
	int					on = 1;
	int					listenfd = -1;

	if((port < 0))
	{
		log_error("The socket_init() argument incorrect!\n");
	}

	listenfd = socket(AF_INET, SOCK_STREAM, 0);
	if (listenfd < 0)
	{
		log_error("Create socket failure:%s\n", strerror(errno));
		rv = -1;
		goto CleanUp;
	}

	setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on , sizeof(on));
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);

	if (listen_ip == NULL)
	{
		servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	}
	else
	{
		if (inet_pton(AF_INET, listen_ip, &servaddr.sin_addr) < 0)
		{
			log_error("Execute inet_pton failure:%s\n", strerror(errno));
			rv = -2;
			goto CleanUp;
		}
	}

	if ((bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) < 0)
	{
		log_error("Bind the IP and port failure:%s\n", strerror(errno));
		rv = -3;
		goto CleanUp;
	}

	listen(listenfd, 50);
	rv = listenfd;
	goto CleanUp;

CleanUp:
	if (rv > 0)
		return listenfd;
	else
		return rv;
}

/* Sets the maximum number of files that can be opened */
void set_socket_rimit(void)
{
	struct rlimit 	limit;
	
	getrlimit(RLIMIT_NOFILE, &limit);
	limit.rlim_cur = limit.rlim_max;
	setrlimit(RLIMIT_NOFILE, &limit);
	
	return;
}


